/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:example/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:hadss_adaptive_video/hadss_adaptive_video.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';

import 'main.dart';

class VideoPlayerPage extends StatefulWidget {
  final String videoUrl;

  const VideoPlayerPage({Key? key, required this.videoUrl}) : super(key: key);

  @override
  State<StatefulWidget> createState() => VideoPlayerPageState();
}

// 视频播放
class VideoPlayerPageState extends State<VideoPlayerPage> with RouteAware {
  late VideoPlayerController _videoController;
  double _videoAspectRatio = 1.0;
  Size _videoSize = Size.zero;
  Size _windowSize = Size.zero;
  late ScreenRotationCallback _rotationListener;

  @override
  void initState() {
    super.initState();
    _rotationListener = (Orientation orientation) {
      if (!FullScreenPlayUtils.isFullScreen &&
          orientation == Orientation.landscape) {
        _enterFullScreen();
      }
    };
    AdaptiveRotation().addRotationListener(_rotationListener);
    _videoController = VideoPlayerController.asset(widget.videoUrl)
      ..initialize().then((value) {
        _videoController.play();
        _videoController.setLooping(true);
        ImmersionInfo info = AdaptiveImmersion().getImmersionInfo(
            context,
            _videoController.value.size,
            context.read<AppState>().defaultBottomNavHeight);
        setState(() {
          _videoAspectRatio = _videoController.value.aspectRatio;
          _videoSize = info.videoSize;
        });
        _updateImmersionUI(info);
        AdaptiveRotation().setNotFullScreen(
            videoSize: _videoSize, screenSize: MediaQuery.of(context).size);
      });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context)!);
    final logicalSize = MediaQuery.of(context).size;
    if (_windowSize != logicalSize) {
      _windowSize = logicalSize;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _updateRule();
      });
    }
  }

  void _updateRule() {
    if (!FullScreenPlayUtils.isFullScreen && mounted) {
      ImmersionInfo info = AdaptiveImmersion().getImmersionInfo(
          context,
          _videoController.value.size,
          context.read<AppState>().defaultBottomNavHeight);
      setState(() {
        _videoSize = info.videoSize;
      });
      _updateImmersionUI(info);
      AdaptiveRotation()
          .setNotFullScreen(videoSize: _videoSize, screenSize: _windowSize);
    }
  }

  // 当页面被其他页面覆盖时调用
  @override
  void didPushNext() {
    super.didPushNext();
    _pauseVideo();
  }

  // 当从其他页面返回时调用
  @override
  void didPopNext() {
    super.didPopNext();
    _resumeVideo();
    AdaptiveRotation().addRotationListener(_rotationListener);
    _updateRule();
  }

  void _pauseVideo() {
    if (_videoController.value.isPlaying) {
      _videoController.pause();
    }
  }

  void _resumeVideo() {
    if (!_videoController.value.isPlaying) {
      _videoController.play();
    }
  }

  void _updateImmersionUI(ImmersionInfo immersionInfo) {
    // 如果状态栏沉浸式，则设置状态栏高度为0
    if (immersionInfo.immersionSetting.isStatusBarImmersive) {
      Provider.of<AppState>(context, listen: false).topBlankHeight = 0;
    } else {
      // 否则，设置状态栏高度为默认值
      Provider.of<AppState>(context, listen: false).topBlankHeight =
          context.read<AppState>().defaultTopHeight;
    }
    // 如果底部导航栏沉浸式，则设置底部导航栏高度为0，颜色为透明
    if (immersionInfo.immersionSetting.isBottomTabImmersive) {
      Provider.of<AppState>(context, listen: false).bottomBlankHeight = 0;
      Provider.of<AppState>(context, listen: false).bottomNavColor =
          Colors.transparent;
    } else {
      // 否则，设置底部导航栏高度为默认值，颜色为黑色
      Provider.of<AppState>(context, listen: false).bottomBlankHeight =
          context.read<AppState>().defaultBottomNavHeight;
      Provider.of<AppState>(context, listen: false).bottomNavColor =
          Colors.black;
    }
  }

  @override
  void dispose() {
    AdaptiveRotation().removeRotationListener(_rotationListener);
    _videoController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (kIsWeb) {
      return _webBuild();
    } else {
      return _deviceBuild();
    }
  }

  Widget _deviceBuild() {
    return Consumer(builder: (context, AppState state, Widget? child) {
      return ClipRect(
        child: Align(
          alignment: Alignment.center,
          widthFactor: 1,
          heightFactor: 1,
          child: SizedBox(
            width: _videoSize.width,
            height: _videoSize.height,
            child: AspectRatio(
              aspectRatio: _videoAspectRatio,
              child: Stack(
                children: [
                  VideoPlayer(_videoController),
                  Align(
                    alignment: Alignment.bottomRight,
                    child: Container(
                        margin: EdgeInsets.only(
                            bottom: 8 + state.defaultBottomNavHeight, right: 8),
                        child: ElevatedButton(
                          onPressed: () {
                            _enterFullScreen();
                          },
                          child: const Text(
                            '全屏',
                            style: TextStyle(color: Colors.white),
                          ),
                        )),
                  )
                ],
              ),
            ),
          ),
        ),
      );
    });
  }

  Widget _webBuild() {
    return AspectRatio(
      aspectRatio: _videoAspectRatio,
      child: OverflowBox(
        maxWidth: double.infinity,
        maxHeight: double.infinity,
        alignment: Alignment.center,
        child: SizedBox(
          width: _videoSize.width,
          height: _videoSize.height,
          child: Stack(
            children: [
              VideoPlayer(_videoController),
              Align(
                  alignment: Alignment.center,
                  child: ElevatedButton(
                    onPressed: () {
                      _enterFullScreen();
                    },
                    child: const Text(
                      '全屏',
                      style: TextStyle(color: Colors.white),
                    ),
                  ))
            ],
          ),
        ),
      ),
    );
  }

  void _enterFullScreen() {
    if (mounted) {
      AdaptiveRotation().removeRotationListener(_rotationListener);
      FullScreenPlayUtils.enterFullScreen(context, _videoController);
    }
  }
}
